package acm.pta5;

import 左哥算法.ch15并查集.UnionFindSet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class T2_4 {
    /**
     * 思路：
     *      构建并查集，
     */
    public static void main(String[] args) throws IOException {
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(in.readLine());
        UnionFindSet<Integer> unionSet=new UnionFindSet<>();
        String[] read=null;
        while (n-- > 0) {
            read=in.readLine().split(" ");
            int pre = Integer.parseInt(read[1]);
            unionSet.init(pre);
            for (int i = 2; i < read.length; i++) {
                int curr = Integer.parseInt(read[i]);
                unionSet.union(pre,curr);
                pre=curr;
            }
        }
        n=Integer.parseInt(in.readLine());
        System.out.println(unionSet.getAllCount()+" "+ unionSet.getSetCount());
        while (n-->0){
            read=in.readLine().split(" ");
            boolean isSame = unionSet.isSameSet(Integer.parseInt(read[0]), Integer.parseInt(read[1]));
            if (isSame){
                System.out.println("Y");
            }else {
                System.out.println("N");
            }
        }
    }
}
